package com.gitee.feizns.explore.data_structure.array.easy;

/**
 * @author feizns
 * @since 2020/3/24
 */
public class ImageSmoother {

    public static void main(String[] args) {
        int[][] ints = imageSmoother(new int[][]{
                {1, 1, 1},
                {1, 0, 1},
                {1, 1, 1}
        });
        for (int i = 0; i < ints.length; i++) {
            for (int j = 0; j < ints[0].length; j++) {
                System.out.print(ints[i][j]);
            }
            System.out.println();
        }
    }

    static int[][] m;

    public static int[][] imageSmoother(int[][] M) {
        m = M;
        int[][] ret = new int[M.length][M[0].length];
        for (int i = 0; i < M.length; i++) {
            for (int j = 0; j < M[0].length; j++) {
                ret[i][j] = ret(i, j);
            }
        }
        return ret;
    }

    static int[][] offset = {
            { -1, -1 }, { -1, 0 }, { -1, 1 },
            {  0, -1 }, {  0, 0 }, {  0, 1 },
            {  1, -1 }, {  1, 0 }, {  1, 1 }
    };

    private static int ret(int i, int j) {
        int sum = 0;
        int n = 0;
        for (int k = 0; k < offset.length; k++) {
            int x = i + offset[k][0];
            int y = j + offset[k][1];
            if ( in(x, y) ) {
                n++;
                sum += m[x][y];
            }
        }
        return sum / n;
    }

    private static boolean in(int i, int j) {
        return i < m.length && i >= 0 && j < m[0].length && j >= 0;
    }

}
